#include "tcp_client.h"

static const char *TAG = "TCP_CLIENT";

void tcp_send_data(char *sendbuf, char *recvbuf,int sleep_time)
{
    MYAPP_LOGD(TAG, "Entering tcp_send_data");

    MYAPP_LOGD(TAG, "Send data :%s", sendbuf);
    send(sock_cli, sendbuf, strlen(sendbuf), 0); ///发送

    char buf[BUFFER_SIZE];
    memset(buf, 0, sizeof(buf));
    sleep(sleep_time);
    recv(sock_cli, buf, sizeof(buf), 0); ///接收
    strcat(recvbuf, buf);

    MYAPP_LOGD(TAG, "Receving data :%s", recvbuf);
}

void tcp_read_data(void)
{
    MYAPP_LOGD(TAG, "Entering tcp_read_data");

    char recvbuf[BUFFER_SIZE];

    recv(sock_cli, recvbuf, sizeof(recvbuf), 0); ///接收
    MYAPP_LOGD(TAG, "Receving data :%s", recvbuf);

    memset(recvbuf, 0, sizeof(recvbuf));
}

void tcp_cycle_readout_data(char *recvbuf)
{
    // MYAPP_LOGD(TAG, "Entering tcp_read_data");

    // char buf[BUFFER_SIZE];
    // memset(buf, 0, sizeof(buf));

    // do
    // {
    //     recv(sock_cli, buf, sizeof(buf), 0); ///接收
    //     strcat(recvbuf, buf);
    // } while (strlen(buf) != 0);

    // MYAPP_LOGD(TAG, "Receving data :%s", recvbuf);
}

void close_connection()
{
    close(sock_cli);
}

int get_connection()
{
    MYAPP_LOGD(TAG, "Entering get_connection");
    // define socket
    sock_cli = socket(AF_INET, SOCK_STREAM, 0);

    // define sockaddr_in
    struct sockaddr_in servaddr;
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(POP3PORT);
    servaddr.sin_addr.s_addr = inet_addr(ip);

    if (connect(sock_cli, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
    {
        return 0;
    }
    return 1;
}

// 1 for success; 0 for failed
int search_dns(char *buf)
{
    MYAPP_LOGD(TAG, "Entering search_dns");
    host = gethostbyname2(buf, AF_INET);
    if (host == 0x0)
    {
        return 0;
    }
    else
    {
        ip = inet_ntoa(*(struct in_addr *)host->h_addr_list[0]);
        MYAPP_LOGD(TAG, "Got ip : %s", ip);
        return 1;
    }
}